package com.mjlf.mjatis.datasource;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
import com.mchange.v2.c3p0.DriverManagerDataSource;
import com.mchange.v2.c3p0.DriverManagerDataSourceFactory;
import com.mjlf.mjatis.alias.Alias;
import com.mjlf.mjatis.alias.AliasUtils;
import com.mjlf.mjatis.config.Configuration;
import com.mjlf.mjatis.exception.DataSourceException;
import com.mjlf.mjatis.util.Json2Entity;
import lombok.extern.java.Log;
import sun.security.krb5.Config;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName DataSourceParser
 * @Author mjlft
 * @Date 2020/5/28 23:58
 * @Version 1.0
 * @Description dataSource解析器
 */
@Log
public class DataSourceParser {

    /**
     * 解析配置文件，并且设置DataSource
     * 考虑怎么做到适配问题
     * @param dataSourceJson
     * @param configuration
     */
    public void parseConfig(JSONObject dataSourceJson, Configuration configuration){
        try {
            Set<String> keys = dataSourceJson.keySet();
            Map<String, Object> map = new HashMap<>((int)(keys.size() / 0.75) + 1);
            keys.stream().forEach(key -> {
                Object obj = dataSourceJson.get(key);
                map.put(key, obj);
            });

            //c3p0 database实例创建， 后续还要接入其他连接池， 这里可以可以选择使用策略模式， 后续需要完善
            DataSource dataSource = DataSources.unpooledDataSource((String)map.get("jdbcUrl"), (String)map.get("username"), (String)map.get("password"));
            dataSource = DataSources.pooledDataSource(dataSource, map);
            if(dataSourceJson != null){
                configuration.setDataSource(dataSource);
            }
        } catch (Exception e) {
            log.info("解析DataSource错误" + dataSourceJson);
            DataSourceException dataSourceException = new DataSourceException("解析DataSource错误" + dataSourceJson);
            dataSourceException.setStackTrace(e.getStackTrace());
            throw dataSourceException;
        }
    }

    public void parseConfig(String basePackagePath, Configuration configuration){

    }

    /**
     * 混合解析
     * @param basePackagePath
     * @param dataSourceJson
     * @param configuration
     */
    public void parseConfig(String basePackagePath, JSONObject dataSourceJson, Configuration configuration){
        parseConfig(dataSourceJson, configuration);
        parseConfig(basePackagePath, configuration);
    }
}
